import 'package:intl/intl.dart';

class Tool {
  static String formatNumber(int number) {
    if (number < 10000) {
      return number.toString();
    }
    // 如果有小数就显示小数，否则显示整数, 0也显示整数
    if (number % 10000 == 0) {
      return '${(number / 10000).toStringAsFixed(0)}W';
    } else {
      return '${(number / 10000).toStringAsFixed(1)}W';
    }
  }

  static String formatTime(String time) {
    if (time.isEmpty) return '';
    DateTime dateTime = DateTime.parse(time);
    DateTime now = DateTime.now();
    Duration difference = now.difference(dateTime);
    if (difference.inMinutes < 60) {
      if (difference.inMinutes == 0) {
        return '刚刚';
      }
      return '${difference.inMinutes}分钟前';
    }
    if (difference.inHours < 24) {
      return '${difference.inHours}小时前';
    }
    // 判断大于一天直接显示日期
    if (difference.inDays > 0) {
      return '${dateTime.year}-${dateTime.month}-${dateTime.day}';
    }
    return time;
  }

  /// 处理手机号
  static String maskPhoneNumber(String phoneNumber) {
    if (phoneNumber.length != 11) {
      return phoneNumber; // 如果手机号不是11位，直接返回原始字符串
    }
    String maskedPhoneNumber = phoneNumber.replaceRange(3, 7, '****');
    return maskedPhoneNumber;
  }

  /// 格式化日期时间，返回 yyyy-MM-dd HH:mm
  static String formatDate(String dateTimeStr, {String format = 'yyyy-MM-dd HH:mm'}) {
    try {
      // 尝试解析时间字符串
      DateTime dateTime = DateTime.parse(dateTimeStr);
      // 格式化为"yyyy-MM-dd HH:mm"
      return DateFormat(format).format(dateTime);
    } catch (e) {
      // 如果解析失败，返回原始字符串
      return dateTimeStr;
    }
  }

  /// 获取星期几
  static String getWeekdayName(DateTime date, {String locale = 'zh'}) {
    const weekdays = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];
    return weekdays[date.weekday % 7];
  }

  /// 获取当前时间戳
  static String getCurrentTimestamp() {
    return DateTime.now().millisecondsSinceEpoch.toString();
  }

  /// 判断是否是邮箱
  static bool isEmail(String email) {
    return RegExp(r'^[^\s@]+@[^\s@]+\.[^\s@]+$').hasMatch(email);
  }
}
